package com.jdd.modules.parkmonthly.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdd.common.api.vo.Result;
import com.jdd.common.constant.JddConstant;
import com.jdd.common.util.LoginUserUtils;
import com.jdd.common.util.RestTemplateUtils;
import com.jdd.common.util.SnowFlakeUtil;
import com.jdd.modules.parking.entity.ParkInfo;
import com.jdd.modules.parking.service.IConfigParkInfoService;
import com.jdd.modules.parking.service.IParkInfoService;
import com.jdd.modules.parkmonthly.dto.MonthlyDepartmentDto;
import com.jdd.modules.parkmonthly.entity.MonthlyCardInfo;
import com.jdd.modules.parkmonthly.entity.MonthlyDepartment;
import com.jdd.modules.parkmonthly.entity.MonthlyDepartmentTreeModel;
import com.jdd.modules.parkmonthly.mapper.MonthlyDepartmentMapper;
import com.jdd.modules.parkmonthly.service.IMonthlyCardInfoService;
import com.jdd.modules.parkmonthly.service.IMonthlyDepartmentService;
import com.jdd.modules.parkmonthly.vo.AddMonthlySpace;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 月卡车部门组织表
 * @Author: jdd
 * @Date:   2021-11-09
 * @Version: V1.0
 */
@Service
@Slf4j
public class MonthlyDepartmentServiceImpl extends ServiceImpl<MonthlyDepartmentMapper, MonthlyDepartment> implements IMonthlyDepartmentService {

    @Resource
    private IParkInfoService parkInfoService;
    @Resource
    private IMonthlyCardInfoService monthlyCardInfoService;
    @Resource
    private IConfigParkInfoService configParkInfoService;
    @Resource
    private RestTemplateUtils restTemplateUtils;

    private  String parkAdminUrl;

    /**
     * @description 查询某一车场下的所有部门，以树形结构展示
     * @date 2021/11/19 9:51
     * @author liushengnan
     * @return java.util.List<com.jdd.modules.parkmonthly.entity.MonthlyDepartmentTreeModel>
     */
    @Override
    public List<MonthlyDepartmentTreeModel> queryTreeList() {
        LambdaQueryWrapper<MonthlyDepartment> query = new LambdaQueryWrapper<MonthlyDepartment>();
        query.orderByAsc(MonthlyDepartment::getSortNo);
//        query.isNull(MonthlyDepartment::getParentId);
//        query.isEm
        query.eq(MonthlyDepartment::getDepartType,JddConstant.IntNumber.INT_ZERO);
        //顶级节点
        List<MonthlyDepartment> firstLevelList = this.list(query);
        // 调用wrapTreeDataToTreeList方法生成树状数据
        List<MonthlyDepartmentTreeModel> listResult = wrapTreeDataToTreeList(firstLevelList);
        log.info("得到的树形结构部门信息如下:{}", JSONObject.toJSONString(listResult));
        return listResult;
    }

    /**
     * @description 查询所有部门信息封装成树形数据
     * @date 2021/11/19 9:52
     * @author liushengnan
     * @param firstLevelList
     * @return java.util.List<com.jdd.modules.parkmonthly.entity.MonthlyDepartmentTreeModel>
     */
    @Override
    public List<MonthlyDepartmentTreeModel> wrapTreeDataToTreeList(List<MonthlyDepartment> firstLevelList) {

        List<MonthlyDepartmentTreeModel> list=new ArrayList<>();
        for(MonthlyDepartment monthlyDepartment:firstLevelList){
            MonthlyDepartmentTreeModel monthlyDepartmentTreeModel=new MonthlyDepartmentTreeModel();
            BeanUtils.copyProperties(monthlyDepartment,monthlyDepartmentTreeModel);
            monthlyDepartmentTreeModel.setKey(monthlyDepartment.getId());
            monthlyDepartmentTreeModel.setTitle(monthlyDepartment.getDepartName());
            monthlyDepartmentTreeModel.setValue(monthlyDepartment.getId());
            getTreeData(monthlyDepartmentTreeModel,list);
            list.add(monthlyDepartmentTreeModel);
        }
        return list;
    }

    @Override
    public Result<MonthlyDepartment> removeChildrenData(MonthlyDepartment monthlyDepartment){
        log.info("removeChildrenData，接收到的参数：{}",JSONObject.toJSONString(monthlyDepartment));
        List<String>lists= new LinkedList<>();
        String parkCode = monthlyDepartment.getParkCode();
        Result<MonthlyDepartment> result=new Result<>();
        //判断当前节点下是否关联了月租信息，monthly_card_info表
        LambdaQueryWrapper<MonthlyCardInfo> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MonthlyCardInfo::getMonthlyDepartmentId,monthlyDepartment.getId());
        List<MonthlyCardInfo> list = monthlyCardInfoService.list(wrapper);
        if(CollectionUtils.isNotEmpty(list)){
            //关联了月租信息
            result.error500("该部门下关联了月租信息，不允许删除");
            return result;
        }
        removeById(monthlyDepartment.getId());
        lists.add(monthlyDepartment.getId());
        //查找当前节点的子节点
        LambdaQueryWrapper<MonthlyDepartment> childrenNodeWrapper=new LambdaQueryWrapper<>();
        childrenNodeWrapper.eq(MonthlyDepartment::getParentId,monthlyDepartment.getId());
        //所有子节点
        List<MonthlyDepartment> childrenList = list(childrenNodeWrapper);
        for (MonthlyDepartment monthlyDepartment1:childrenList){
            //删除节点系统需判断本节点及子节点是否被人员信息关联，关联人员信息不允许删除
            removeChildrenData(monthlyDepartment1);
        }
        result.success("删除成功");
        return result;
    }

    /**
     * @description 查询当前节点下的所有子节点封装成树形数据
     * @date 2021/11/19 9:56
     * @author liushengnan
     * @param monthlyDepartmentTreeModel
     * @param list
     * @return void
     */
    @Override
    public void getTreeData(MonthlyDepartmentTreeModel monthlyDepartmentTreeModel,List<MonthlyDepartmentTreeModel> list){
        //查找当前节点的子节点
        LambdaQueryWrapper<MonthlyDepartment> childrenNodeWrapper=new LambdaQueryWrapper<>();
        childrenNodeWrapper.orderByAsc(MonthlyDepartment::getSortNo);
        childrenNodeWrapper.eq(MonthlyDepartment::getParentId,monthlyDepartmentTreeModel.getId());
        //所有子节点
        List<MonthlyDepartment> childrenList = list(childrenNodeWrapper);
        List<MonthlyDepartmentTreeModel> list1=new ArrayList<>();
        for (MonthlyDepartment monthlyDepartment1:childrenList){
            MonthlyDepartmentTreeModel monthlyDepartmentTreeModel1=new MonthlyDepartmentTreeModel();
            BeanUtils.copyProperties(monthlyDepartment1,monthlyDepartmentTreeModel1);
            monthlyDepartmentTreeModel1.setKey(monthlyDepartmentTreeModel1.getId());
//                monthlyDepartmentTreeModel1.setValue();
            monthlyDepartmentTreeModel1.setTitle(monthlyDepartmentTreeModel1.getDepartName());
            monthlyDepartmentTreeModel1.setLeaf(true);
            monthlyDepartmentTreeModel1.setValue(monthlyDepartmentTreeModel1.getId());
            list1.add(monthlyDepartmentTreeModel1);

            getTreeData(monthlyDepartmentTreeModel1,new ArrayList<MonthlyDepartmentTreeModel>());
        }
        monthlyDepartmentTreeModel.setChildren(list1);
//        list.add(monthlyDepartmentTreeModel);

    }

    /**
     * @description 校验部门名称是否重复并调用部门封装方法
     * @date 2021/11/19 9:57
     * @author liushengnan
     * @param monthlyDepartmentDto
     * @return com.jdd.common.api.vo.Result<com.jdd.modules.parkmonthly.entity.MonthlyDepartment>
     */
    @Override
    public Result<MonthlyDepartment> addDepartment(MonthlyDepartmentDto monthlyDepartmentDto) {
        log.info("新增部门/组织信息，传入参数为----------------------》：{}",monthlyDepartmentDto);
        String parkCode = monthlyDepartmentDto.getParkCode();
        Result<MonthlyDepartment> result=new Result<>();
        MonthlyDepartment monthlyDepartment = new MonthlyDepartment();
        if(verifyOnly(monthlyDepartmentDto)){
            result.error500("部门信息重复，请修改！");
        }
        MonthlyDepartment monthlyDepartEntity = getMonthlyDepartEntitys(monthlyDepartmentDto, monthlyDepartment);
        log.info("新增部门/组织信息，新增结果---------------------》:{}",monthlyDepartment);
        result.success("添加成功！");
        return result;
    }

//    @Override
//    public Result addSameGroup(MonthlyDepartmentDto monthlyDepartmentDto) {
//        log.info("新增同级部门信息，传入参数为----------------------》：{}",monthlyDepartmentDto);
//        MonthlyDepartment monthlyDepartment = new MonthlyDepartment();
//        if(verifyOnly(monthlyDepartmentDto)){
//            Result.genFailResult("部门信息重复，请修改！");
//        }
//        if(monthlyDepartmentDto.getDepartType() != JddConstant.IntNumber.INT_ONE){
//            monthlyDepartment.setParentId(this.getById(monthlyDepartmentDto.getId()).getParentId());
//        }
//        getMonthlyDepartEntity(monthlyDepartmentDto,monthlyDepartment);
//        log.info("新增同级部门信息，新增结果---------------------》:{}",monthlyDepartment);
//        this.save(monthlyDepartment);
//        return Result.genSuccessResult();
//    }
//
//    @Override
//    public Result addSonGroup(MonthlyDepartmentDto monthlyDepartmentDto) {
//        log.info("新增子级部门信息，传入参数为----------------------》：{}",monthlyDepartmentDto);
//        MonthlyDepartment monthlyDepartment = new MonthlyDepartment();
//        if(verifyOnly(monthlyDepartmentDto)){
//            Result.genFailResult("部门信息重复，请修改！");
//        }
//        monthlyDepartment.setParentId(monthlyDepartmentDto.getId());
//        getMonthlyDepartEntity(monthlyDepartmentDto,monthlyDepartment);
//        log.info("新增子级部门信息，新增结果---------------------》:{}",monthlyDepartment);
//        return Result.genSuccessResult();
//    }
//
    /**
     * @description 删除节点，子节点也需删除。删除节点系统需判断本节点及子节点是否被人员信息关联，关联人员信息不允许删除
     * @date 2021/11/19 9:15
     * @author liushengnan
     * @param id
     * @return com.jdd.common.api.vo.Result<com.jdd.modules.parkmonthly.entity.MonthlyDepartment>
     */
    @Override
    public Result<MonthlyDepartment> deleteDepartment(String id) {
        log.info("删除部门信息，传入参数为----------------------》,id:{}",id);
        MonthlyDepartment monthlyDepartment = getById(id);
        Result<MonthlyDepartment> result = removeChildrenData(monthlyDepartment);
        return result;
    }

    /**
     * @Title: verifyOnly
     * @Description:封装月租部门信息并保存
     * @author: zjf
     * @date 2021年11月14日
     * @version 1.0
     */
    @Override
    public void getMonthlyDepartEntity(MonthlyDepartmentDto monthlyDepartmentDto,MonthlyDepartment monthlyDepartment){

            ParkInfo parkInfo = parkInfoService.getParkInfoByParkCode();
            monthlyDepartment.setId(SnowFlakeUtil.getId());
            monthlyDepartment.setDepartName(monthlyDepartmentDto.getDepartName());
            if(StringUtils.isNotEmpty(monthlyDepartmentDto.getParentId())){
                monthlyDepartment.setParentId(monthlyDepartmentDto.getParentId());
                //查询父组件是几级菜单
                MonthlyDepartment monthlyDepartmentParent = getById(monthlyDepartmentDto.getParentId());
                monthlyDepartment.setDepartType(monthlyDepartmentParent.getDepartType()+1);
            }else{
                monthlyDepartment.setDepartType(JddConstant.IntNumber.INT_ZERO);
            }
            if(null!=parkInfo) {
                monthlyDepartment.setParkCode(parkInfo.getParkCode());
                monthlyDepartment.setParkName(parkInfo.getParkName());

                //获取当前车场一级部门的最大sortNo
                LambdaQueryWrapper<MonthlyDepartment> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(MonthlyDepartment::getParkCode,parkInfo.getParkCode());
                if(StringUtils.isNotEmpty(monthlyDepartment.getParentId())){
                    wrapper.eq(MonthlyDepartment::getParentId,monthlyDepartment.getParentId());
                }
                wrapper.eq(MonthlyDepartment::getDepartType,monthlyDepartment.getDepartType());
                wrapper.orderByDesc(MonthlyDepartment::getSortNo);
                List<MonthlyDepartment> list = list(wrapper);
                if(CollectionUtils.isNotEmpty(list)){
                    monthlyDepartment.setSortNo( list.get(0).getSortNo()+1);
                }else{
                    monthlyDepartment.setSortNo(JddConstant.IntNumber.INT_ZERO);
                }
                monthlyDepartment.setCreateTime(new Date());
                monthlyDepartment.setCreateBy(LoginUserUtils.getLoginUser().getUsername());
                save(monthlyDepartment);
            }


    }

    /**
     * @Title: verifyOnly
     * @Description:封装月租部门信息并保存
     * @author: zjf
     * @date 2021年11月14日
     * @version 1.0
     */
     private MonthlyDepartment getMonthlyDepartEntitys(MonthlyDepartmentDto monthlyDepartmentDto,MonthlyDepartment monthlyDepartment){

        ParkInfo parkInfo = parkInfoService.getParkInfoByParkCode();
        monthlyDepartment.setId(SnowFlakeUtil.getId());
        monthlyDepartment.setDepartName(monthlyDepartmentDto.getDepartName());
        if(StringUtils.isNotEmpty(monthlyDepartmentDto.getParentId())){
            monthlyDepartment.setParentId(monthlyDepartmentDto.getParentId());
            //查询父组件是几级菜单
            MonthlyDepartment monthlyDepartmentParent = getById(monthlyDepartmentDto.getParentId());
            monthlyDepartment.setDepartType(monthlyDepartmentParent.getDepartType()+1);
        }else{
            monthlyDepartment.setDepartType(JddConstant.IntNumber.INT_ZERO);
        }
        if(null!=parkInfo) {
            monthlyDepartment.setParkCode(parkInfo.getParkCode());
            monthlyDepartment.setParkName(parkInfo.getParkName());

            //获取当前车场一级部门的最大sortNo
            LambdaQueryWrapper<MonthlyDepartment> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(MonthlyDepartment::getParkCode,parkInfo.getParkCode());
            if(StringUtils.isNotEmpty(monthlyDepartment.getParentId())){
                wrapper.eq(MonthlyDepartment::getParentId,monthlyDepartment.getParentId());
            }
            wrapper.eq(MonthlyDepartment::getDepartType,monthlyDepartment.getDepartType());
            wrapper.orderByDesc(MonthlyDepartment::getSortNo);
            List<MonthlyDepartment> list = list(wrapper);
            if(CollectionUtils.isNotEmpty(list)){
                monthlyDepartment.setSortNo( list.get(0).getSortNo()+1);
            }else{
                monthlyDepartment.setSortNo(JddConstant.IntNumber.INT_ZERO);
            }
            monthlyDepartment.setCreateTime(new Date());
            monthlyDepartment.setCreateBy(LoginUserUtils.getLoginUser().getUsername());
            save(monthlyDepartment);
        }

        return monthlyDepartment;
    }
    /**
     * @Title: verifyOnly
     * @Description:验证单个车场组下车场组姓名是否唯一
     * @author: zjf
     * @date 2021年10月14日
     * @version 1.0
     */
    @Override
    public boolean verifyOnly(MonthlyDepartmentDto req){
        QueryWrapper<MonthlyDepartment> queryWrapper = new QueryWrapper<MonthlyDepartment>();
        queryWrapper.eq("depart_name", req.getDepartName());
        queryWrapper.eq("park_code", req.getParkCode());
        int count = this.count(queryWrapper);
        if(count > 0){
            return true;
        }
        return false;
    }

    /**
     * @description 根据部门id查询当前部门的所有上级部门并拼接返回
     * @date 2021/12/17 10:05
     * @author liushengnan
     * @param departmentId
     * @return java.lang.String
     */
    @Override
    public String getDepartmentNameChain(String departmentId){
//        StringBuilder departmentChainStrBuilder=new StringBuilder();
//        this.getParentDepartment(departmentId,departmentChainStrBuilder);
//        if(StringUtils.isNotEmpty(departmentChainStrBuilder.toString())){
//            return departmentChainStrBuilder.substring(0,departmentChainStrBuilder.length()-1);
//        }else{
//            return departmentChainStrBuilder.toString();
//        }


        List<String> list =new ArrayList<>();
        this.getParentDepartment(departmentId,list);
        Collections.reverse(list);
        String departmentStrChain = String.join("/", list);
        return departmentStrChain;
    }

    /**
     * @description 递归查询所有父部门
     * @date 2021/12/17 9:58
     * @author liushengnan
     * @param id
     * @return com.jdd.modules.parkmonthly.entity.MonthlyDepartment
     */
    @Override
    public void getParentDepartment(String id,List<String> list){
//        MonthlyDepartment monthlyDepartment = this.getById(id);
//        if(null!=monthlyDepartment){
//            departmentChainStrBuilder.append(monthlyDepartment.getDepartName()+"/");
//            getParentDepartment(monthlyDepartment.getParentId(),departmentChainStrBuilder);
//        }

        MonthlyDepartment monthlyDepartment = this.getById(id);
        if(null!=monthlyDepartment){
            list.add(monthlyDepartment.getDepartName());
            getParentDepartment(monthlyDepartment.getParentId(),list);
        }
    }

    @Override
    public void requestCloudMonthlyDepartment(String parkCode) {

        AddMonthlySpace addMonthlySpace = new AddMonthlySpace();
        addMonthlySpace.setJudge(false);
        addMonthlySpace.setStr(parkCode);
        ResponseEntity<Result> post = restTemplateUtils.post("", addMonthlySpace, Result.class);
        Result body = post.getBody();
        Object result = body.getResult();
        String str = JSONObject.toJSONString(result);
        List<MonthlyDepartment> monthlyDepartments = JSONArray.parseArray(str, MonthlyDepartment.class);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("park_code",parkCode);
        this.remove(queryWrapper);
        this.saveBatch(monthlyDepartments);
    }
}
